package com.heima.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();

        //白名单
        String[] strs = {
                "login.jsp",
                "register.jsp",
                "/css/",
                "/imgs/",
                "LoginServlet",
                "RegisterServlet",
                "CheckCodeServlet"
        };
        //获取访问路径
        String requestURI = request.getRequestURI();
        //判断路径是否在白名单内
        for (String str : strs) {
            if (requestURI.contains(str)){
                filterChain.doFilter(request,response);
                return;
            }
        }
        //判断是否登陆
        Object user = session.getAttribute("user");
        if (user != null){
            filterChain.doFilter(request,response);
            return;
        }
        //跳转登陆界面
        response.sendRedirect("login.jsp");

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
